#include "cv.h"
#include "highgui.h"
#include <string>

using namespace std;

/**
 * function declartion : mouse call back 
 */
void myMouseCallback(int event, int x, int y, int flags, void* param);

CvRect box;
bool isDraw = false; //flag

/**
 * draw a rect to a image
 * @param: IplImage* image : the background image
 *		   CvRect rect : the painted rectangle
 * @return: 
 */
void drawBox(IplImage* image, CvRect rect){
	cvRectangle(image, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height), cvScalar(0, 0, 255));
}

/**
 * main
 * @param: 
 * @return: 
 */
void main(){
	box = cvRect(-1, -1, 0, 0);
	//init background image
	IplImage* image = cvCreateImage(cvSize(800, 600), IPL_DEPTH_8U, 3);
	cvZero(image);
	IplImage* imageTemp = cvCloneImage(image);
	//init window
	string windowName = "drawBox";
	cvNamedWindow(windowName.data(), CV_WINDOW_AUTOSIZE);
	
	//set mouse callback
	cvSetMouseCallback(windowName.data(), myMouseCallback, (void*)image);

	//main loop
	while (1) {
		cvCopyImage(image, imageTemp);
		if (isDraw) {
			drawBox(imageTemp, box);
		}
		cvShowImage(windowName.data(), imageTemp);
		
		//break
		if (cvWaitKey(15) == 27 ) {
			break;
		}
	}

	//release
	cvReleaseImage(&image);
	cvReleaseImage(&imageTemp);
	cvDestroyWindow(windowName.data());
}

/**
 * mouse call back function
 * @param: 
 * @return: 
 */
void myMouseCallback(int event, int x, int y, int flags, void* param){
	IplImage* image = (IplImage*) param;
	//mouse button handle
	switch(event){
	case CV_EVENT_MOUSEMOVE:{
		if (isDraw) {
			box.width = x - box.x;
			box.height = y - box.y;
		}
							}
							break;
	case CV_EVENT_LBUTTONDOWN:{
		isDraw = true;
		box = cvRect(x, y, 0, 0);
							}
							break;
	case CV_EVENT_LBUTTONUP:{
		isDraw = false;
		if (box.width < 0) {
			box.x = box.x + box.width;
			box.width = -box.width;
		}
		if (box.height < 0) {
			box.y = box.y + box.height;
			box.height = -box.height;
		}
		drawBox(image, box);
							}
							break;

	}
}